package com.bida.service.impl;

import com.bida.constant.OrdersConstant;
import com.bida.domain.dto.GoodsSalesDTO;
import com.bida.domain.po.Orders;
import com.bida.domain.vo.*;
import com.bida.mapper.OrderDetailMapper;
import com.bida.mapper.OrdersMapper;
import com.bida.mapper.UserMapper;
import com.bida.service.IOrdersService;
import com.bida.service.ReportService;
import com.bida.service.WorkspaceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatisticsInfo(LocalDate begin, LocalDate end) {
        // 获取日期列表
        ArrayList<LocalDate> dateList = getAllDate(begin,end);
        //存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 获取当天开始结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 获取当天营业额
            Double turnover = ordersMapper.getTurnoverStatisticsInfo(beginTime, endTime,OrdersConstant.COMPLETED);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        //封装返回结果
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatisticsInfo(LocalDate begin, LocalDate end) {
        // 获取日期列表
        ArrayList<LocalDate> dateList = getAllDate(begin,end);
        // 准备数据
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            Map map = new HashMap();
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            map.put("endTime",endTime);
            Integer totalUser = userMapper.getUserCountByTime(map);
            totalUserList.add(totalUser);
            map.put("beginTime",beginTime);
            Integer newUser = userMapper.getUserCountByTime(map);
            newUserList.add(newUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }



    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatisticsInfo(LocalDate begin, LocalDate end) throws Exception {
        OrderReportVO orderReportVO = new OrderReportVO();

        // 获取日期列表
        ArrayList<LocalDate> dateList = getAllDate(begin,end);
        ArrayList<Integer> orderCountList = new ArrayList<>();
        ArrayList<Integer> validOrderCountList = new ArrayList<>();

        // 获取订单总数
        CompletableFuture<Integer> allCountFuture = CompletableFuture.supplyAsync(() ->
                ordersService.lambdaQuery()
                        .gt(Orders::getOrderTime, begin.atStartOfDay())
                        .le(Orders::getOrderTime, end.atStartOfDay().plusDays(1))
                        .count());

        // 获取有效订单数
        CompletableFuture<Integer> completedCountFuture = CompletableFuture.supplyAsync(() ->
                ordersService.lambdaQuery()
                        .eq(Orders::getStatus, OrdersConstant.COMPLETED)
                        .gt(Orders::getOrderTime, begin.atStartOfDay())
                        .le(Orders::getOrderTime, end.atStartOfDay().plusDays(1))
                        .count());

        // 获取每日订单状态数
        CompletableFuture<Object> objectCompletableFuture = CompletableFuture.supplyAsync(() -> {
            for (LocalDate date : dateList) {
                LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
                // 获取每日订单数
                orderCountList.add(ordersService.lambdaQuery()
                        .gt(Orders::getOrderTime, beginTime)
                        .le(Orders::getOrderTime, endTime)
                        .count());
                // 获取每日订单完成数
                validOrderCountList.add(ordersService.lambdaQuery()
                        .eq(Orders::getStatus, OrdersConstant.COMPLETED)
                        .gt(Orders::getOrderTime, beginTime)
                        .le(Orders::getOrderTime, endTime)
                        .count());
            }
            return null;
        });
        // 阻塞等待所有线程执行完毕
        CompletableFuture.allOf(allCountFuture, completedCountFuture,objectCompletableFuture).join();
        // 获取订单完成率
        Double orderCompletionRate = allCountFuture.get() == 0 ? 0.0 : Double.valueOf(completedCountFuture.get()) / Double.valueOf(allCountFuture.get());

        orderReportVO.setDateList(StringUtils.join(dateList,","));
        orderReportVO.setOrderCountList(StringUtils.join(orderCountList,","));
        orderReportVO.setValidOrderCountList(StringUtils.join(validOrderCountList,","));
        orderReportVO.setTotalOrderCount(allCountFuture.get());
        orderReportVO.setValidOrderCount(completedCountFuture.get());
        orderReportVO.setOrderCompletionRate(orderCompletionRate);
        return orderReportVO;
    }

    /**
     * 查询销量排名top10接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10Infos(LocalDate begin, LocalDate end) {
        List<GoodsSalesDTO> goodsSalesDTO = orderDetailMapper.getTop10Infos(begin.atStartOfDay(), end.atStartOfDay().plusDays(1));

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(goodsSalesDTO.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ","))
                .numberList(StringUtils.join(goodsSalesDTO.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ","))
                .build();
    }

    /**
     * 导出Excel报表接口( 30天数据 )
     */
    @Override
    public void exportReportExcelDate(HttpServletResponse response) {
        LocalDate startDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        // 查询数据
        BusinessDataVO businessDataVO =  workspaceService.getBusinessData(startDate.atStartOfDay(),endDate.atStartOfDay().plusDays(1));
        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            // 基于模板文件创建新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            // 获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            // 填充 时间 范围
            sheet.getRow(1).getCell(1).setCellValue("时间" + startDate + "至" + endDate);
            // 获取第4，5行概览数据（总计）
            XSSFRow row4 = sheet.getRow(3);
            XSSFRow row5 = sheet.getRow(4);
            row4.getCell(2).setCellValue(businessDataVO.getTurnover());
            row4.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row4.getCell(6).setCellValue(businessDataVO.getNewUsers());
            row5.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row5.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            ArrayList<LocalDate> dateList = new ArrayList<>();
            dateList.add(startDate);
            while (!startDate.equals(endDate)){
                startDate = startDate.plusDays(1);
                dateList.add(startDate);
            }

            for (int i = 0; i < dateList.size(); i++) {
                // 获取当日日期
                LocalDate date = dateList.get(i);
                // 获取当日数据
                BusinessDataVO businessData = workspaceService.getBusinessData(date.atStartOfDay(), date.atStartOfDay().plusDays(1));
                // 封装当前行数据
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            // 释放资源，防止内存泄露
            out.close();
            excel.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 获取日期时间
     * @param begin
     * @param end
     * @return
     */
    private ArrayList<LocalDate> getAllDate(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}
